package organizer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;

/**
 *
 * @author dawong
 */
public class FileUtils {

    private static final Logger log = Logger.getLogger(FileUtils.class);

    private FileUtils() {

    }

    /**
     * Create an md5sum hash of the entire contents of a file.
     * 
     * @param file
     * @return 
     */
    public static String hash(File file) {
        String ret = "";
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            DigestInputStream in = new DigestInputStream(fin,
                    MessageDigest.getInstance("MD5"));
            byte[] buff = new byte[1024];
            int len = -1;
            while ((len = in.read(buff)) >= 0);
            byte[] results = in.getMessageDigest().digest();
            ret = Hex.encodeHexString(results);
        } catch (IOException ex) {
            log.error(null, ex);
        } catch (NoSuchAlgorithmException ex) {
            log.error(null, ex);
        } finally {
            try {
                if (fin  != null)
                    fin.close();
            } catch (IOException ex) {
                log.error(null, ex);
            }
        }
        return ret;
    }

    /**
     * Create an md5 sum hash of only the beginning of a file.
     * @param file
     * @param size
     * @return 
     */
    public static String sampleHash(File file, int size) {
        String ret = "";
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            DigestInputStream in = new DigestInputStream(fin,
                    MessageDigest.getInstance("MD5"));
            byte[] buff = new byte[size];
            in.read(buff);
            byte[] results = in.getMessageDigest().digest();
            ret = Hex.encodeHexString(results);
        } catch (IOException ex) {
            log.error(null, ex);
        } catch (NoSuchAlgorithmException ex) {
            log.error(null, ex);
        } finally {
            try {
                if (fin != null)
                    fin.close();
            } catch (IOException ex) {
                log.error(null, ex);
            }
        }
        return ret;
    }
    
    /**
     * Delete files/directories recursively.
     * @param file 
     */
    public static void recursiveDelete(File file) {
        if (file.isFile()) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    recursiveDelete(f);
                }
            }
        }
    }

}
